<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

require_once('database.php');
require_once('parameters.php');

$db = new database('localhost', 'root', '', 'reebonz');

function get_db_products() {
    global $db;
    $db->query('SELECT * FROM products JOIN events ON products.event_id=events.event_id');
    return $db->getList();
}

function get_category($brand, $product) {
	$categories = array(" bag "=>array("pomikaki", "dior", "tod's", "givenchy"),
				"toy"=>array("noodoll"), "glasses"=>array("ray ban"), "watch"=>array("swap rebel", "slip watch"), "others"=>array("other", "cuisipro"),
				"wallet"=>array("prada", "dior"));

	$str = " ".strtolower($product["name"]." ".$product["title"])." ";
	foreach ($categories as $category=>$list) {
		if ($category !== 'others' && strpos($str, $category) !== false) return $category;
	}

	foreach ($categories as $category) {
		foreach ($category as $element) {
			if ($brand == $element) return $category;
		}	
	}
	return "others";
}

function get_brand($product) {
	$brands = array("cuisipro", "pomikaki", "noodoll", "prada", "dior", "tod's", "givenchy", "ray ban", "swap rebel", "slip watch");
	$str = strtolower($product["name"]." ".$product["title"]);
	foreach ($brands as $brand) {
		if (strpos($str, $brand) !== false) return $brand;
	}	
	return "other";
}

function same_category($product1, $product2) {
	$brand1 = get_brand($product1);
	$brand2 = get_brand($product2);
	if (get_category($brand1, $product1) == get_category($brand2, $product2)) return true;
	return false;
}

function cmp($p1, $p2) {
	if ($p1['rank'] < $p2['rank']) return -1;
	if ($p1['rank'] < $p2['rank']) return 0;
	return 1;
}

function get_related_products($product_id) {
	global $db; 
	$db->query('SELECT * FROM products JOIN events ON products.event_id=events.event_id WHERE product_id = %d',$product_id);
	$product = $db->getRow();
	$products = get_db_products();
	$res = array();
	foreach ($products as $other_product) {
		if (same_category($product, $other_product) && $product["product_id"] != $other_product["product_id"]) {
			$res[$other_product['pid']] = $other_product;
			$res[$other_product['pid']]['rank'] = abs($product["sell_price"] - $other_product["sell_price"]);
		}
	}
	usort($res, "cmp");
	return $res;
}
?>
